import {
  App,
  Controller,
  Get,
  Inject,
  Provide
} from '@midwayjs/decorator';
import { Application, Context } from 'egg';
// 路径
const path = require('path');

//node.js 文件操作对象
const fs = require('fs');
// 获取mime
const mime = require('mime-types'); //需npm安装

@Provide()
@Controller('/')
export class HomeController {
  @Inject()
  ctx: Context;

  @App()
  app: Application
  
  @Get('/')
  async home() {
    return 'Hello Midwayjs!';
  }
  /**
   * 获取上传的头像
   */
  @Get('/*')
  async getPublic(){
    let url = path.join(this.app.config.baseDir, this.ctx.url);
    let file = null;
    try {
	    file = fs.readFileSync(url); //读取文件
    } catch (error) {
        //如果服务器不存在请求的图片，返回默认图片
        url = path.join(this.app.config.baseDir, '/public/default.png')  //默认图片地址
        file = fs.readFileSync(url); //读取文件	    
    }
    let mimeType = mime.lookup(url); //读取图片文件类型
    this.ctx.set('content-type', mimeType); //设置返回类型
    this.ctx.body = file; //返回图片

  }
}
